//
//  SelectDateVC.swift
//  mmda
//
//  Created by 李陆涛 on 2018/5/29.
//  Copyright © 2018年 mmda. All rights reserved.
//

import UIKit


protocol SelectDateVCDelegate: class {
    
    func didSelect(_ date: Date)
}

class SelectDateVC: UIViewController {
    
    
    @IBOutlet weak var viewBottom: NSLayoutConstraint!
    @IBOutlet weak var datePicker: UIDatePicker!
    
    weak var delegate:SelectDateVCDelegate?
    var selectDate:Date?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        setupUI()
    }
    
    func setupUI() {
        
        
        self.view.backgroundColor = UIColor.init(white: 0, alpha: 0.2)
        self.viewBottom.constant = 200
        
        let now = Date.init()
        
        datePicker.maximumDate = now
        datePicker.locale = Locale(identifier: "zh_Hans_CN")
        
        let yearBefore100 =  Date.init(timeIntervalSince1970: now.timeIntervalSince1970 - (100 * 365 * 24 * 3600))
        
        datePicker.minimumDate = yearBefore100
        
        self.view.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(dismissView)))
        
        self.datePicker.setDate(selectDate ?? Date.init(), animated: true)
    }
    
    
    
    @IBAction func dateChangedAction(_ sender: UIDatePicker) {
        
        self.delegate?.didSelect(sender.date)
    }
    
    @IBAction func commitAction(_ sender: Any) {
        
        self.dismissView()
    }
    
    func showView(_ viewcontroller:UIViewController) {
        
        self.modalPresentationStyle = .overCurrentContext
        
        viewcontroller.present(self, animated: false) {
            
            [weak self] in
            guard let `self` = self else { return }
            
            self.makeAnimation(0)
        }
    }
    
    @objc func dismissView () {
        
        DispatchQueue.main.after(0.25) {
            
            [weak self] in
            guard let `self` = self else { return }
            
            self.dismiss(animated: false, completion: nil)
        }
        makeAnimation(200)
    }
    
    func makeAnimation(_ height:CGFloat) {
        
        self.viewBottom.constant = height
        
        UIView.animate(withDuration: 0.25) {
            
            [weak self] in
            guard let `self` = self else { return }
            
            self.view.layoutIfNeeded()
        }
    }
}



